﻿// <copyright file="OpenDatabaseButton.cs" company="City of Portland, BES-ASM">
// </copyright>
// <summary>OpenDatabaseButton class</summary>

namespace BESASM.EMGAATS.UI.ArcMap
{
  using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Text;
  using System.Windows.Forms;
  using BESASM.EMGAATS.Arc;
  using BESASM.EMGAATS.BusinessClasses;
  using BESASM.EMGAATS.DataAccess;
  using ESRI.ArcGIS.Catalog;
  using ESRI.ArcGIS.CatalogUI;
  using ESRI.ArcGIS.Geodatabase;

  /// <summary>
  /// A button for opening the EMGAATS Master database.
  /// </summary>
  public class OpenDatabaseButton : ESRI.ArcGIS.Desktop.AddIns.Button
  {
    /// <summary>
    /// Called when the button is clicked by ArcMap
    /// </summary>
    protected override void OnClick()
    {
      FormsUtility.SafeExecute(delegate
      {
        ArcMap.Application.CurrentTool = null;
        this.InternalOnClick();
      });
    }

    /// <summary>
    /// Called when controls are updated by ArcMap.
    /// </summary>
    protected override void OnUpdate()
    {
      this.Enabled = ArcMap.Application != null;
    }

    private void InternalOnClick()
    {
      IGxDialog gxDialog = new GxDialogClass();
      gxDialog.Title = "Open EMGAATS Database";
      gxDialog.ObjectFilter = new WorkspaceFilterWrapper();

      IWorkspace workspace = null;
      IEnumGxObject workspaces = null;
      try
      {
        if (gxDialog.DoModalOpen(ArcMap.Application.hWnd, out workspaces) && workspaces != null)
        {
          IGxObject gxObject = workspaces.Next();
          if (gxObject is IGxDatabase)
          {
            IGxDatabase gxDatabase = (IGxDatabase)gxObject;
            workspace = gxDatabase.Workspace;
          }
        }
        else
        {
          return;
        }
      }
      finally
      {
        ComUtility.ReleaseComObject(workspaces);
      }

      if (workspace != null)
      {
        EmgaatsExtension.OpenDatabase(workspace);
      }
      else
      {
        FormsUtility.ShowWarning("Invalid workspace selected.");
      }
    }
  }
}
